﻿using SolidWorks.Interop.sldworks;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using System.Drawing;
using SwAssem.Plugin;
using SwHelper.DocHelper;
using SolidWorks.Interop.swconst;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;

namespace SwAssem
{
    partial class MainWindow
    {
        #region 界面选择效果
        [DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool DeleteObject([In] IntPtr hObject);

        public ImageSource ImageSourceForBitmap(string filepath)
        {
            int pic_size = 256;
            Bitmap bmp = WindowsThumbnailProvider.GetThumbnail(filepath, pic_size, pic_size, ThumbnailOptions.None);

            var handle = bmp.GetHbitmap();
            try
            {
                ImageSource newSource = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

                DeleteObject(handle);
                return newSource;
            }
            catch (Exception ex)
            {
                DeleteObject(handle);
                return null;
            }
        }

        private void OnTreeViewItemSelectedChange(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeViewItem _item = (TreeViewItem)this.AssemTree.SelectedItem;
            if (_item == null) return;

            Component2 component2 = _item.Tag as Component2;
            if (component2 == null) return;

            ModelDoc2 _doc = Swapp.IActiveDoc2;
            SelectionMgr selMrg = _doc.ISelectionManager;
            SelectData selData = selMrg.CreateSelectData();
            selData.Mark = 0;
            component2.Select4(false, selData, false);
        }
        private void OnTreeMenuItemClick(object sender, RoutedEventArgs e)
        {
            TreeViewItem selItem = AssemTree.SelectedItem as TreeViewItem;
            Component2 component2 = selItem.Tag as Component2;
            if(selItem == null || component2 == null)
            {
                MessageBox.Show("请先选择装配节点");
                return;
            }
            string filepath = component2.GetPathName();
            string endext = "sldprt";
            if(!filepath.ToLower().EndsWith(endext))
            {
                MessageBox.Show("仅可添加零件");
                return;
            }

            MenuItem menuItem1 = (MenuItem)sender;
            if(menuItem1.Name == "ADD1")
            {
                Panle2_image.Tag = selItem.Tag;
                this.Panle2_image.Source = ImageSourceForBitmap(filepath);

                UpdateDatum(Panle2_listbox1, component2, 1);
            }
            else if(menuItem1.Name == "ADD2")
            {
                Panle3_imge.Tag = selItem.Tag;
                this.Panle3_imge.Source = ImageSourceForBitmap(filepath);

                UpdateDatum(Panle3_listbox1, component2, 1);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="listbox"></param>
        /// <param name="component"></param>
        /// <param name="type"> type=1基准；type=2边 type=3面</param>
        private void UpdateDatum(ListBox listbox, Component2 component, int type)
        {
            if (component == null) return;

            listbox.Items.Clear();

            IDocHelper dochelper = DocHelperA.GetDocHelper(Swapp);
            if (type == 1)
            {
                object listFeat = null;
                dochelper.AskDatums(component.GetModelDoc2(), out listFeat);
                object[] listfeature = listFeat as object[];
                foreach(object obj in listfeature)
                {
                    Feature feat = obj as Feature;

                    ListBoxItem listitem = new ListBoxItem();
                    listitem.Content = feat.Name;
                    listitem.Tag = feat;
                    listbox.Items.Add(listitem);
                }
            }else if(type == 2)
            {
                object listEdges;
                dochelper.AskEdges((PartDoc)component.GetModelDoc2(), out listEdges);
                object[] edges = (object[])listEdges;
                for(int i=0; i<edges.Length; i++)
                {
                    object obj = edges[i];
                    ListBoxItem listitem = new ListBoxItem();
                    listitem.Content = "Edge_" + i.ToString();
                    listitem.Tag = obj;
                    listbox.Items.Add(listitem);
                }
            }
            else if(type == 3)
            {
                object listFaces;
                dochelper.AskFaces((PartDoc)component.GetModelDoc2(), out listFaces);
                object[] faces = (object[])listFaces;
                for(int i=0; i<faces.Length; i++)
                {
                    object obj = faces[i];
                    Face2 face2 = obj as Face2;
                    ListBoxItem listitem = new ListBoxItem();
                    listitem.Content = "face_" + i.ToString();
                    listitem.Tag = face2;
                    listbox.Items.Add(listitem);
                }

            }      
        }

        private void RadioButton_CheckedA(object sender, RoutedEventArgs e)
        {
            Component2 component2 = this.Panle2_image.Tag as Component2;
            if (component2 == null) return;
            RadioButton radiobtn = (RadioButton)sender;
            if(radiobtn.Content.ToString() == "基准")
            {
                UpdateDatum(Panle2_listbox1, component2, 1);
            }else if(radiobtn.Content.ToString() == "边")
            {
                UpdateDatum(Panle2_listbox1, component2, 2);
            }else if(radiobtn.Content.ToString() == "面")
            {
                UpdateDatum(Panle2_listbox1, component2, 3);
            }

        }
        private void RadioButton_CheckedB(object sender, RoutedEventArgs e)
        {
            Component2 component2 = this.Panle3_imge.Tag as Component2;
            if (component2 == null) return;
            RadioButton radiobtn = (RadioButton)sender;
            if (radiobtn.Content.ToString() == "基准")
            {
                UpdateDatum(Panle3_listbox1, component2, 1);
            }
            else if (radiobtn.Content.ToString() == "边")
            {
                UpdateDatum(Panle3_listbox1, component2, 2);
            }
            else if (radiobtn.Content.ToString() == "面")
            {
                UpdateDatum(Panle3_listbox1, component2, 3);
            }
        }
        private void Listbox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ModelDoc2 modeldoc2 = Swapp.ActiveDoc;

            ListBox listbox = (ListBox)sender;
            ListBoxItem listitem = listbox.SelectedItem as ListBoxItem;
            if (listitem == null) return;
            object objTag = listitem.Tag;
            if (objTag == null) return;

            SelectData seldata = modeldoc2.ISelectionManager.CreateSelectData();
            seldata.Mark = 0;
            modeldoc2.ClearSelection2(true);
       
            bool boolstatue = ((Entity)objTag).Select4(false, seldata);

            modeldoc2.Rebuild((int)swRebuildOptions_e.swRebuildAll);
        }

        private void OpenSelPartDlg(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "模型|*.sldprt";
            sfd.ShowDialog();
            string filePath = sfd.FileName;
            if (File.Exists(filePath))
            {
                object obj1 = this.Panle2_image.Tag;
                object obj2 = this.Panle3_imge.Tag;

                System.Windows.Controls.Image tempImage = null;
                AssemblyDoc assemblydoc = null;

                if(btn.Name == "Panle2_Btn1")
                {
                    tempImage = this.Panle2_image;
                    if (obj2 == null)
                        assemblydoc = Swapp.ActiveDoc as AssemblyDoc;
                    else
                    {
                        Component2 component2 = obj2 as Component2;
                        component2 = component2.GetParent();
                        if(component2 == null)
                        {
                            assemblydoc = Swapp.ActiveDoc;
                        }else
                        {
                            assemblydoc = component2.GetModelDoc2() as AssemblyDoc;
                        }
                    }
                }else if(btn.Name == "Panle3_Btn1")
                {
                    tempImage = this.Panle3_imge;
                    if (obj1 == null)
                        assemblydoc = Swapp.ActiveDoc as AssemblyDoc;
                    else
                    {
                        Component2 component2 = obj1 as Component2;
                        component2 = component2.GetParent();
                        if(component2 == null)
                        {
                            assemblydoc = Swapp.ActiveDoc;
                        }else
                        {
                            assemblydoc = component2.GetModelDoc2() as AssemblyDoc;
                        }
                    }
                }
                int IntError = 0;
                int IntWraning = 0;

                ModelDoc2 currentModldoc = Swapp.ActiveDoc;
                ModelDoc2 tempDoc = assemblydoc as ModelDoc2;
                if (currentModldoc != tempDoc)
                {
                    tempDoc = assemblydoc as ModelDoc2;
                    Swapp.ActivateDoc(tempDoc.GetPathName());
                }else
                {
                    tempDoc = null;
                }

                #region 打开需要被插入的零件
                ModelDoc2 SwPartDoc = (ModelDoc2)Swapp.OpenDoc6(filePath, (int)swDocumentTypes_e.swDocPART, 0, "", ref IntError, ref IntWraning);
                #endregion

                //#region B.往装配体中插入零件PlugButton.SLDPRT。
                Component2 SwComp = assemblydoc.AddComponent5(filePath, 0, "", false, "", 0, 0, 0);
                if(SwComp != null)
                {
                    Swapp.CloseDoc(SwPartDoc.GetTitle());
                    tempImage.Tag = SwComp;
                    UpdateDatum(Panle3_listbox1, SwComp, 1);
                    tempImage.Source = ImageSourceForBitmap(filePath);

                }
                if(tempDoc != null)
                {
                    Swapp.CloseDoc(tempDoc.GetTitle());
                }
                Swapp.ActivateDoc(currentModldoc.GetPathName());
            }
        }

        private void AddMateBtnClick(object sender, RoutedEventArgs e)
        {
            ListBoxItem selListboxItem1 = Panle2_listbox1.SelectedItem as ListBoxItem;
            ListBoxItem selListboxItem2 = Panle3_listbox1.SelectedItem as ListBoxItem;

            if(selListboxItem1 == null )
            {
                MessageBox.Show("请选择装配对象一装配条件");
                return;
            }
            if(selListboxItem2 == null)
            {
                MessageBox.Show("请选择装配对象二装配条件");
                return;
            }
            object selobj1 = selListboxItem1.Tag;
            object selobj2 = selListboxItem2.Tag;

            ModelDoc2 currentModeldoc = Swapp.ActiveDoc;
            ModelDoc2 parentModeldoc = null;
            object obj1 = this.Panle2_image.Tag;
            object obj2 = this.Panle3_imge.Tag;
            if(obj2 != null)
            {
                Component2 component = obj2 as Component2;
                Component2 parentCom = component.GetParent();
                if(parentCom != null)
                {
                    parentModeldoc = parentCom.GetModelDoc2();
                    Swapp.ActivateDoc(parentModeldoc.GetTitle());
                }
            }else
            {
                MessageBox.Show("未知错误：line315 in MainWinControl.cs");
                return;
            }
            Component2 comp1 = obj1 as Component2;
            Component2 comp2 = obj2 as Component2;
            string str1 = comp1.Name2;
            string str2 = comp2.Name2;

            ModelDoc2 tempdoc = Swapp.ActiveDoc;
            string str3 = tempdoc.GetPathName();
            str3 = Path.GetFileNameWithoutExtension(str3);
            tempdoc.ClearSelection2(true);
            SelectionMgr selMgr = tempdoc.SelectionManager;
            SelectData selData = selMgr.CreateSelectData();
            selData.Mark = 1;

            Feature feat1 = selobj1 as Feature;
            Feature feat2 = selobj2 as Feature;

            bool selstatues = false;
            if (feat1 != null && feat2 != null)
            {
                string name1 = feat1.Name + "@" + str1 + "@" + str3;
                string name2 = feat2.Name + "@" + str2 + "@" + str3;

                //需要做类型区分
                selstatues = tempdoc.Extension.SelectByID2(name1, "PLANE", 0, 0, 0, true, -1, null, 0);
                selstatues = tempdoc.Extension.SelectByID2(name2, "PLANE", 0, 0, 0, true, -1, null, 0);
            }else
            {                
                ((Entity)selobj1).Select4(false, selData);
                ((Entity)selobj2).Select4(true, selData);

                MessageBox.Show("未实现通过对象进行选中");
                return;
            }

            int swMateEnum = 0;
            string cbItem1 = MateCombobox.SelectionBoxItem as string;
            if (cbItem1 == "重合")
            {
                swMateEnum = 0;
            }

            int longstatus = 0;
            AssemblyDoc swAssembly = ((AssemblyDoc)(tempdoc));
            Mate2 swMate = swAssembly.AddMate5(swMateEnum, 1, false, 0, 0.001, 0.001, 0.001, 0.001, 0, 0, 0, false, false, 0, out longstatus);
            tempdoc.ClearSelection2(true);
            tempdoc.EditRebuild3();

            if(parentModeldoc !=null)
            {
                Swapp.CloseDoc(parentModeldoc.GetTitle());
                Swapp.ActivateDoc(currentModeldoc.GetTitle());
            }
        }

        #endregion
    }
}
